package com.example.demo.aop;

import com.example.demo.annotation.Idempotent;
import com.example.demo.keyresolver.IdempotentKeyResolver;
import com.example.demo.utils.CollectionUtils;
import com.example.demo.utils.GlobalErrorCodeConstants;
import com.example.demo.utils.JsonUtils;
import com.example.demo.utils.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 拦截声明了 {@link Idempotent} 注解的方法，实现幂等操作
 *
 * @author houp
 */
@Aspect
@Slf4j
@Component
public class IdempotentAspect {

    /**
     * IdempotentKeyResolver 集合
     */
    private final Map<Class<? extends IdempotentKeyResolver>, IdempotentKeyResolver> keyResolvers;

    // private final IdempotentRedisDAO idempotentRedisDAO;

    // public IdempotentAspect(List<IdempotentKeyResolver> keyResolvers, IdempotentRedisDAO idempotentRedisDAO) {
    public IdempotentAspect(List<IdempotentKeyResolver> keyResolvers) {
        this.keyResolvers = CollectionUtils.convertMap(keyResolvers, IdempotentKeyResolver::getClass);
        // this.idempotentRedisDAO = idempotentRedisDAO;
    }

    @Before("@annotation(idempotent)")
    public void before(JoinPoint joinPoint, Idempotent idempotent) {
        // 获得 IdempotentKeyResolver
        IdempotentKeyResolver keyResolver = keyResolvers.get(idempotent.keyResolver());
        Assert.notNull(keyResolver, "找不到对应的 IdempotentKeyResolver");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 解析 Key
        String key = keyResolver.resolver(request, joinPoint, idempotent);
        log.info(key);
        // 锁定 Key。
        // boolean success = idempotentRedisDAO.setIfAbsent(key, idempotent.timeout(), idempotent.timeUnit());
        boolean success = true;
        log.info("[方法({}) 参数({})]", joinPoint.getSignature().toString(), JsonUtils.toJson(joinPoint.getArgs()));
        // 锁定失败，抛出异常
        if (!success) {
            log.info("[方法({}) 参数({}) 存在重复请求]", joinPoint.getSignature().toString(), JsonUtils.toJson(joinPoint.getArgs()));
            throw new ServiceException(GlobalErrorCodeConstants.REPEATED_REQUESTS.getCode(), idempotent.message());
        }
    }

}
